package com.aaa.service;

import com.aaa.dao.TuserMapper;
import com.aaa.entity.MyPage;
import com.aaa.entity.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

@Service
public class TuserServiceImpl implements TuserService{

    @Resource
    private TuserMapper tuserMapper;
    @Override
    public boolean addUser(User user) {
        int insert=-1;
        if(user.getId()==null) {
            // 添加的时候   创建时间
            user.setCreatetime(new Date());
            // 盐
            String salt = UUID.randomUUID().toString();
            // 密码要求的是密文
            // md5
            // 12345 +salt
            String oldpwd = user.getPassword() + salt;
            String newpassword = DigestUtils.md5DigestAsHex(oldpwd.getBytes());
            user.setSalt(salt);
            user.setPassword(newpassword);
             insert = tuserMapper.insert(user);
        }else{
            insert = tuserMapper.updateByPrimaryKey(user);
        }



        return insert>=0?true:false;
    }

    @Override
    public PageInfo queryAll(MyPage myPage, User user) {
        PageHelper.startPage(myPage.getPage(),myPage.getLimit());

        PageInfo pageInfo = new PageInfo(tuserMapper.queryAll(user));
        return pageInfo;
    }

    @Override
    public boolean updUser(User user) {
        //根据id修改状态
        int i = tuserMapper.updateByPrimaryKeySelective(user);
        return i>0?true:false;
    }

    @Override
    public boolean queryByName(String username) {
        User user = new User();
        user.setUsername(username);
        User user1 = tuserMapper.selectOne(user);
        return user1==null;
    }

    @Override
    public User login(User user) {
        // 页面获取的密码  123456
        //1. 根据名字  查询用户的信息
        Example example = new Example(User.class);
        //.andEqualTo("deptno", 10).
        //example.createCriteria().andBetween("deptno", 10, 22);
        example.createCriteria().andEqualTo("username",user.getUsername());
        example.and().andEqualTo("status",1);
             //example.setOrderByClause("deptno desc");
        User user1 = tuserMapper.selectOneByExample(example);
        // 2. 如果有  比对一下输入的密码和数据库中的密码是否一致
        if(user1!=null) {
            //   2.1 输入的密码进行同样的加盐加密方式   盐  数据库里面查出来的密码进行比对
            String password = user.getPassword();
            String salt = user1.getSalt();
            // 根据输入的密码进行加盐加密之后的数据
            String s = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (s.equals(user1.getPassword())) {
                return user1;
            }
        }
        return null;
    }
}
